//
//  EDSAppDelegateTool.m
//  DriveSchoolCoach
//
//  Created by TangBin on 2019/7/5.
//  Copyright © 2019 TangBin. All rights reserved.
//

#import "EDSAppDelegateTool.h"
#import "TYZNavRootVCInfo.h"
#import "TYZNetworkConfig.h"
#import "TYZBaseViewController.h"
//#import "EDSMoLocationManager.h"
//#import <LeanCloudObjc/Foundation.h>
//#import "ZTDBManager.h"
//#import "WXApi.h"
//#import "TYZLogManager.h"
//#import "WDLocationManager.h" // 定位


@interface EDSAppDelegateTool () <UITabBarControllerDelegate>
@property (nonatomic, assign) BOOL isFirst; ///< 用户安装app不是第一次打开
@property (nonatomic, assign) EDS_NETWORK_STATUS networkStatus; ///< 网络状态

/// 点击tabBarItem的时间
@property (nonatomic, strong) NSDate *lastDate;

/// 随机数
@property (nonatomic, assign) NSInteger randomNumber;

//@property (nonatomic, strong) AMapLocationManager *locationManager;

@end

@implementation EDSAppDelegateTool

+ (instancetype)sharedInstance
{
    static EDSAppDelegateTool *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    return instance;
}

- (instancetype)init
{
    if (self = [super init])
    {
        [self setup];
    }
    return self;
}

- (void)setup
{
    [self setupUUID];
    // 网络监听
    [self monitorReachabilityStatus];
    id first = [EDSUtility objectForKey:@"isFirst"];
    if (!first)
    {// 这里有可能是用户曾经使用过app，删除了，后来有安装了。
        [TYZKeychain remove:kUserInfo];
        self.isFirst = NO;
        [EDSUtility setObject:@(self.isFirst) forKey:@"isFirst"];
    }
    else
    {
        self.isFirst = [first boolValue]; // 不是第一次打开
    }
    // 设置网络请求的根地址
    [TYZNetworkConfig sharedConfig].baseUrl = kBaseUrl;
    // 用户信息
    id userInfoModel = [TYZKeychain load:kUserInfo];
    if (userInfoModel)
    {
//        self.userInfoModel = userInfoModel;
    }
    [self setSvProgressHUD];
//    [self registerAPNS];
    // 百度初始化
//    [self setupBaidu];
    
    // 高德初始化
    [self setupGaode];
    
    //友盟
    [self setupUM];
    // 微信初始化
    [self setupWXApi];
//    [self setupBugly];
    
    // 初始化定位
//    [[WDLocationManager shareInstance] configLocationManager];
    
    [self setNavBarAppearence];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    // 监听重新返回APP
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillResignAction) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 网络状态监控
        [self setupNetworkStatusChange];
    });
}

#pragma mark 高德初始化
- (void)setupGaode
{
//    [self setGaode:GDKey];
//    self.genViewModel = [[GeneralViewModel alloc]init];
//    [self.genViewModel requestMapAccountCompletion:^(EDSRespondDataEntity * _Nonnull respond) {
//        if(respond.code == EDS_NETWORK_SUCCESS){
//            NSString *key = respond.data;
//            [self setGaode:key];
//        }else{
//            [self setGaode:GDKey];
//        }
//    }];
}
-(void)setGaode:(NSString *)key
{
    /*
    [AMapServices sharedServices].apiKey = key;
    [AMapServices sharedServices].enableHTTPS = YES;
    [MAMapView updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    [MAMapView updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.locationTimeout = 2;
    self.locationManager.reGeocodeTimeout = 2;
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    @weakify(self);
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        @strongify(self);
        if (error)
        {
            if (error.code == AMapLocationErrorLocateFailed)
            {
                self.city = @"合肥市";
                self.latitude = 31.86694;
                self.longitude = 117.2827;
                return;
            }
        }
        if (regeocode) {
            self.city = regeocode.city;
            self.address = [NSString stringWithFormat:@"%@%@",regeocode.province,regeocode.city];
            self.latitude = location.coordinate.latitude;
            self.longitude = location.coordinate.longitude;
            
            // 临时加上
//            [AppContext getInstance].city = @"合肥市";
//            [AppContext getInstance].lat = 31.86694;
//            [AppContext getInstance].lon = 117.2827;
        } else {
            self.city = @"合肥市";
            self.latitude = 31.86694;
            self.longitude = 117.2827;
        }
    }];
     */
}

/// 微信初始化
- (void)setupWXApi
{
    /*
    if (![WXApi isWXAppInstalled])
    {
        return;
    }
    BOOL ret = [WXApi registerApp:kWEIXIN_APP_ID universalLink:kWEIXIN_APP_UNIVERSAL_LINK];
    if (ret)
    {
        debugLog(@"微信sdk初始化成功");
    }
    */
    /*
     WXULCheckStepParams,
     WXULCheckStepSystemVersion,
     WXULCheckStepWechatVersion,
     WXULCheckStepSDKInnerOperation,
     WXULCheckStepLaunchWechat,
     WXULCheckStepBackToCurrentApp, --- 5
     WXULCheckStepFinal,
     */
//    [WXApi checkUniversalLinkReady:^(WXULCheckStep step, WXCheckULStepResult * _Nonnull result) {
//
//        NSString *log = [NSString stringWithFormat:@"微信测试函数：%@, state=%u, errorInfo=%@, 修正建议=%@", @(step), result.success, result.errorInfo, result.suggestion];
//        debugLog(@"%@", log);
////        [[TYZLogManager sharedInstance] logInfo:@"" logStr:log, nil];
//    }];
}

/**
 唯一标识码
 */
- (NSString *)setupUUID
{
    NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString *uuid = [TYZKeychain load:bundleId];
    if ([objectNull(uuid) isEqualToString:@""])
    {
        uuid = [NSString stringWithUUID];
        [TYZKeychain save:bundleId data:uuid];
    }
    return uuid;
}

- (NSString *)deviceId
{
    return [self setupUUID];
}

- (void)setNavBarAppearence
{
    // 设置是 广泛使用WRNavigationBar，还是局部使用WRNavigationBar，目前默认是广泛使用
//    [WRNavigationBar wr_widely];
    //    [WRNavigationBar wr_setBlacklist:@[@"SpecialController",
    //                                       @"TZPhotoPickerController",
    //                                       @"TZGifPhotoPreviewController",
    //                                       @"TZAlbumPickerController",
    //                                       @"TZPhotoPreviewController",
    //                                       @"TZVideoPlayerController"]];
    
    // 设置导航栏默认的背景颜色
//    [WRNavigationBar wr_setDefaultNavBarBarTintColor:kNavBarBackgroundColor];
    // 设置导航栏所有按钮的默认颜色
//    [WRNavigationBar wr_setDefaultNavBarTintColor:[UIColor whiteColor]];
    // 设置导航栏标题默认颜色
//    [WRNavigationBar wr_setDefaultNavBarTitleColor:[UIColor whiteColor]];
    // 统一设置状态栏样式
//    [WRNavigationBar wr_setDefaultStatusBarStyle:UIStatusBarStyleLightContent];
    
    // 如果需要设置导航栏底部分割线隐藏，可以在这里统一设置
//    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
}

//注册推送 //推送的形式：标记，声音，提示
-(void)registerAPNS
{
    /*
    if (TARGET_IPHONE_SIMULATOR)
    {
        return;
    }
    
    // 注册推送
    if (@available(iOS 10.0, *))
    {
        // iOS10及以上注册远程通知的方法
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        // 必须写代理，不然无法监听通知的接收与点击
        center.delegate = self;
        [center requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // 点击允许
                debugLog(@"注册成功");
                
                [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                    debugLog(@"settings=%@", settings);
                }];
            } else {
                // 点击不允许
                debugLog(@"注册失败");
                
            }
        }];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else if (@available(iOS 8.0, *)) {
        // iOS8-iOS10注册远程通知的方法
        UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        // 在iOS8之前注册远程通知的方法，如果项目中要支持iOS8之前的版本，必须要写此方法
        UIRemoteNotificationType types = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
    }
    
//    [UNUserNotificationCenter requestAuthorizationWithOptions:completionHandler:] and -[UNUserNotificationCenter setNotificationCategories:]
    
//    //        NSLog(@"tb--注册推送");
//    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
//                                                                         settingsForTypes:(UIUserNotificationTypeSound |
//                                                                                           UIUserNotificationTypeAlert |
//                                                                                           UIUserNotificationTypeBadge)
//                                                                         categories:nil]];
//    [[UIApplication sharedApplication] registerForRemoteNotifications];
     */
}

/**
 百度初始化
 */
- (void)setupBaidu
{
    
}

/**
 初始友盟
 */
- (void)setupUM
{
    
    //友盟
//    [UMConfigure initWithAppkey:kUM_STATISTICAL_KEY_ID channel:@"App Store"];
#ifdef DEBUG
//    [[UMSocialManager defaultManager] openLog:YES];
#else
#endif
}

- (void)setupBugly
{
//    BuglyConfig *config = [[BuglyConfig alloc] init];
//    config.debugMode = YES;
//    [Bugly startWithAppId:@"6d3ce83b38" config:config];
}
/// 网络状态改变
- (void)setupNetworkStatusChange
{
    
}

/**
 登录视图控制器初始化
 */
- (void)setupLoginVC
{
    // 登录页面
    /*if (!_loginNav)
    {
        TYZNavInfo *navInfo = [[TYZNavInfo alloc] initWithNavBackgroundColor:kNavBarBackgroundColor titleFont:kNavBarTitleFont titleColor:kNavBarTitleColor];
        UIViewController *loginVC =nil;
        loginVC = [[TYZRouter sharedInstance] getLoginVC:nil];
        _loginNav = [[TYZBaseNavigationController alloc] initWithRootViewController:loginVC];
        [_loginNav setupNavCommonInfo:navInfo];
    }*/
}

/**
 主控制器初始化
 */
- (void)setupMainVC
{
    if (!_rootTabBar)
    {
        // 到站服务
        TYZNavRootVCInfo *arrivalServiceInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"首页" clsName:nil imgNorName:@"ic_tab_main_nor" imgSelName:@"ic_tab_main_sel"];
//        arrivalServiceInfo.vc = [[TYZRouter sharedInstance] getRootArrivalServiceVC:nil];
        
        // 外出救援
        TYZNavRootVCInfo *goutRescueInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"外出救援" clsName:nil imgNorName:@"ic_tab_rescue_nor" imgSelName:@"ic_tab_rescue_sel"];
//        goutRescueInfo.vc = [[TYZRouter sharedInstance] getRootGoutRescueVC:nil];
        
        // 扫码
//        TYZNavRootVCInfo *scanCodesInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"扫码" clsName:nil imgNorName:@"ic_tab_main_nor" imgSelName:@"ic_tab_main_sel"];
//        scanCodesInfo.vc = [[TYZRouter sharedInstance] getRootScanCodesVC:nil];

        // 工单
        TYZNavRootVCInfo *workOrderInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"工单" clsName:nil imgNorName:@"ic_tab_order_nor" imgSelName:@"ic_tab_order_sel"];
//        workOrderInfo.vc = [[TYZRouter sharedInstance] getRootWorkOrderVC:nil];
        
        // 我的
        TYZNavRootVCInfo *mineInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"我的" clsName:nil imgNorName:@"ic_tab_mine_nor" imgSelName:@"ic_tab_mine_sel"];
//        mineInfo.vc = [[TYZRouter sharedInstance] getRootMineVC:nil];
        
        _rootTabBar = [[TYZCustomTabBarController alloc] initWithShowMiddleBtn:NO midNorImgName:nil midSelImgName:nil];
        _rootTabBar.delegate = self;
        NSArray *vcs = @[arrivalServiceInfo, goutRescueInfo, workOrderInfo, mineInfo];
        
        TYZNavInfo *navInfo = [[TYZNavInfo alloc] initWithNavBackgroundColor:kNavBarBackgroundColor titleFont:kNavBarTitleFont titleColor:kNavBarTitleColor];
        
        [_rootTabBar setupChildViewController:vcs navInfo:navInfo];
        [_rootTabBar setupTabBarItemTextAttributes:kTabBarItemTitleNorColor selTitleColor:kTabBarItemTitleSelColor titleFont:kTabBarItemTitleFont];
    }
    else
    {
        self.rootTabBar.selectedIndex = 0;
    }
}

/// 登录
- (void)presentLogin
{
    if (self.loginNav)
    {
        self.loginNav = nil;
    }
    [self setupLoginVC];
    [TYZJumpVCManager presentBaseVC:self.window.rootViewController presentVC:_loginNav completion:nil];
}

- (void)updateRootVC
{
    /*
    if (self.userInfoModel.loginState == 1)
    {// 已经登录
        [self setupMainVC];
        self.window.rootViewController = _rootTabBar;
    }
    else
    {// 没有登录
        [self setupLoginVC];
        self.window.rootViewController = _loginNav;
//        [TYZJumpVCManager presentBaseVC:self.window.rootViewController presentVC:_loginNav completion:nil];
    }
    */
    
    /*
    [self setupMainVC];
    _rootTabBar.selectedIndex = 0;
    self.window.rootViewController = _rootTabBar;
     */
    
//    debugLog(@"currname=%@", [[XJRingLetterManager shareInstance] currentUsername]);
    
    /*
    [[XJRingLetterManager shareInstance] logout:^(EMError * _Nonnull error) {
        debugLog(@"error=%@", error);
        debugLog(@"dd");
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[XJRingLetterManager shareInstance] loginWithUserName:@"1000" password:@"@fansyun.cn:12345" completion:^(NSString * _Nonnull aUsername, EMError * _Nonnull aError) {
            debugLog(@"ausername=%@", aUsername);
        }];
    });*/
}

/// 判断是否登录
/// @param vc vc description
- (BOOL)isLogin:(UIViewController *)vc
{
//    if (!self.userInfoModel || self.userInfoModel.loginState == 0) {
//        UIViewController *loginvC = [[TYZRouter sharedInstance] getLoginVC:nil];
//        [TYZJumpVCManager pushBaseVC:vc pushVC:loginvC];
//        return NO;
//    }
    return YES;
}

/**
 进入前台的通知
 
 @param noti noti description
 */
- (void)appWillEnterForeground:(NSNotification *)noti
{
//    [SVProgressHUD showInfoWithStatus:@"进入前台的通知"];
}

- (void)onAppWillResignAction
{
//    [SVProgressHUD showInfoWithStatus:@"onAppWillResignAction"];
}

- (void)onAppBecomeActive
{
//    [SVProgressHUD showInfoWithStatus:@"onAppBecomeActive"];
}


#pragma mark - 网络监听
/**
 监听网络状态的方法
 */
- (void)monitorReachabilityStatus
{
    @weakify(self);
    // 开始监听
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 网络状态改变回调
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        @strongify(self);
        switch (status)
        {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
//                debugLog(@"蜂窝网络");
                self.networkStatus = EDS_NETWORK_STATUS_WWAN;
            }break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
//                debugLog(@"WIFI");
                self.networkStatus = EDS_NETWORK_STATUS_WIFI;
            } break;
            case AFNetworkReachabilityStatusNotReachable:
            {
//                debugLog(@"没有网络");
                self.networkStatus = EDS_NETWORK_STATUS_NOT;
            } break;
            default:
            {
//                debugLog(@"未知");
                self.networkStatus = EDS_NETWORK_STATUS_NOT;
            } break;
        }
    }];
}




- (void)setSvProgressHUD
{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
    [SVProgressHUD setMinimumDismissTimeInterval:1.5];
}



// 当文件名为中文时，解决url编码问题
- (NSString *)URLDecodedString:(NSString *)str
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

- (NSString *)getUUID
{
    NSString *uuid = [TYZKeychain load:@"com.lingxiao.formeditor"];
    debugLog(@"uuid从缓存读取=%@", uuid);
    if (!uuid) {
        debugLog(@"uuid 是新生成的");
        uuid = [NSString stringWithUUID];
        [TYZKeychain save:@"com.lingxiao.formeditor" data:objectNull(uuid)];
    }
    return uuid;
}


#pragma mark - 用户登录 退出登录 调用


/**
 删除用户信息
 */
- (void)removeUserInfo
{
    [TYZKeychain remove:kUserInfo];
//    self.userInfoModel = nil;
}

/// 登录成功
- (void)loginSuccess {
    
}

/**
 用户退出登录成功
 */
- (void)loginOutSuccess
{
//    self.userInfoModel.loginState = 0;
    [self removeUserInfo];
}


#pragma mark - UITabBarControllerDelegate
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    self.TabSelectedIndex = tabBarController.selectedIndex;
    TYZBaseViewController *vc = tabBarController.selectedViewController;
    NSDate *date = [[NSDate alloc] init];
    if ([vc isEqual:viewController])
    {
        // 处理双击事件
        if (date.timeIntervalSince1970 - _lastDate.timeIntervalSince1970 < 0.5)
        {
            debugLog(@"双击事件");
        }
        _lastDate = date;
    }
    
    debugLog(@"TabSelectedIndex=%zd", self.TabSelectedIndex);
    
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
//    debugLog(@"dddddddd");
    return YES;
}

/// 拉取微信客服
- (void)openWXCustomerService
{
//    if (![WXApi isWXAppInstalled])
//    {
//        [SVProgressHUD showInfoWithStatus:@"您需要安装微信APP"];
//        return;
//    }
//    WXOpenCustomerServiceReq *req = [[WXOpenCustomerServiceReq alloc] init];
//    req.corpid = kWEIXIN_CORP_ID; // 企业id
//    req.url = kWEIXIN_CUSTOMER_SERVICE; // 客服url
//    [WXApi sendReq:req completion:nil];
}



@end

























